#!/bin/sh /etc/rc.common
# Copyright (C) 2015 OpenWrt.org

START=90
STOP=10

USE_PROCD=1
PROG=/usr/sbin/freshclam
FRESHCLAM_CONFIGFILE="/tmp/clamav/freshclam.conf"

validate_freshclam_section() {
	uci_validate_section freshclam freshclam "${1}" \
		'freshclam_config_file:string' \
		'UpdateLogFile:string' \
		'DatabaseMirror:string' \
		'NotifyClamd:string' \
		'DatabaseOwner:string' \
		'CompressLocalDatabase:string' \
		'DatabaseDirectory:string:'
}

start_service() {
	local freshclam_config_file UpdateLogFile DatabaseOwner NotifyClamd DatabaseMirror \
	DatabaseDirectory

	validate_freshclam_section freshclam || {
		echo "validation failed"
		return 1
	}

	[ -f /tmp/freshclam.pid ] && echo "already running" && return 0

	mkdir -p $DatabaseDirectory
	mkdir -p /etc/clamav
	touch /tmp/freshclam.log
	touch /tmp/freshclam.pid

	mkdir -p $(dirname $FRESHCLAM_CONFIGFILE)
	ln -sf $freshclam_config_file $FRESHCLAM_CONFIGFILE

	echo "UpdateLogFile " $UpdateLogFile > $FRESHCLAM_CONFIGFILE
	echo "DatabaseMirror " $DatabaseMirror >> $FRESHCLAM_CONFIGFILE
	echo "NotifyClamd " $NotifyClamd >> $FRESHCLAM_CONFIGFILE
	echo "DatabaseOwner " $DatabaseOwner >> $FRESHCLAM_CONFIGFILE
	echo "CompressLocalDatabase " $CompressLocalDatabase >> $FRESHCLAM_CONFIGFILE
	echo "DatabaseDirectory " $DatabaseDirectory >> $FRESHCLAM_CONFIGFILE

	procd_open_instance
	procd_set_param command $PROG -d --config-file=$FRESHCLAM_CONFIGFILE -p /tmp/freshclam.pid --no-warnings
	procd_set_param file $FRESHCLAM_CONFIGFILE
	procd_close_instance
}

stop_service()
{
	[ ! -f /tmp/freshclam.pid ] && echo "not running" && return 0
	PID=`cat /tmp/freshclam.pid`
	kill $PID
	rm -f /tmp/freshclam.pid
}

service_triggers()
{
	procd_add_reload_trigger "freshclam"
	procd_add_validation validate_freshclam_section
}
